# -*- coding: utf-8 -*-
# @Time: 2021/5/16 15:32
# @Author: moxinqian
# @Contact: tel 18382469064
# @File: index.py
# @DESC:
from flask import Flask, request, render_template
from flask_cors import *
import json
import time
import pandas as pd
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
CORS(app, supports_credentials=True)
import os


def load_data():
    now = time.strftime('%Y-%m-%d', time.localtime())
    data_path = './data/'+now+'-链家新房'
    #如果当天数据没有，则获取前一天的数据
    if os.path.exists(data_path)is False:
        pre_now =time.strftime('%Y-%m-%d', time.localtime(time.time()-86400))
        data_path = './data/' + pre_now + '-链家新房'

    #如果前一天的数据也没有发现，则说明还没有开始爬取

    if os.path.exists(data_path) is False:
        return None
    data = []
    #打开文件遍历数据
    with open(data_path, 'r', encoding='utf-8') as f:
        while True:
            item = f.readline()
            if item == '':
                break
            else:
               _item = json.loads(item)
               _item['num'] = 1
               if (len(_item['position']) == 0):
                   continue
               _item['position_new'] = _item['position'][0]
               # print(_item)
               data.append(_item)
    df = pd.DataFrame(data)
    df_group = df.groupby(by=['position_new'])['num'].sum().sort_values(ascending=True)
    xticks = df_group.index.values
    y = df_group.values
    result = {}
    result['area'] = xticks.tolist()
    result['num'] = y.tolist()
    return result

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/get_data", methods=['GET'])
def get_data():
    result = load_data()
    return json.dumps(result), 200

# 用于docker健康监测
@app.route("/health_check", methods=['GET'])
def test():
    # 初始化视频流
    return 'success!', 200


if __name__ == "__main__":
    # print(time.localtime())
    # print(time.localtime(time.time()-86400))
    # print(load_data())
    app.debug = True
    app.run(host="0.0.0.0", port=5000)